package com.regex.web.filter;

import java.io.IOException;
import java.util.LinkedHashMap;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;

import com.regex.web.cache.DictCacheService;

@WebFilter(urlPatterns = "/sys/*", filterName = "dictFilter")
public class DictFilter implements Filter {
	
	
	private static long dict_session_time = 60*60*1000l;
	
	private static long set_session_time = 0l;
	
	@Autowired
    private DictCacheService dictCacheService;
	
	@Override
    public void init(FilterConfig filterConfig) throws ServletException {
 
    }
	
	@Override
	@SuppressWarnings("unchecked")
	public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain)
			throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;
        // 解决 'X-Frame-Options' to 'deny
        // response.setHeader("X-Frame-Options", "SAMEORIGIN");
		LinkedHashMap<String, Object> dictMap = (LinkedHashMap<String, Object>) request.getSession().getAttribute("dictMap");
        long currentTime = System.currentTimeMillis();
        if(dictMap == null || dictMap.size() == 0 || (currentTime - set_session_time > dict_session_time)) {
            set_session_time = System.currentTimeMillis();
            dictMap = dictCacheService.getDictCache();
        	request.getSession().setAttribute("dictMap", dictMap);
        }
        
		chain.doFilter(request,response);
	}
	
	@Override
    public void destroy() {
 
    }
	
}
